package com.vitaf.cash.app.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.lifecycle.lifecycleScope
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.vitaf.cash.app.R
import com.vitaf.cash.app.base.app.VitafActStackManager
import com.vitaf.cash.app.common.VitafComAct
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.databinding.VitafActVerifyMobilePageBinding
import com.vitaf.cash.app.event.VitafEventData
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.event.room.VitafPointManager
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.dialog.VitafSubmitSuccessDlog
import com.vitaf.cash.app.ui.dialog.VitafTipsDlog
import com.vitaf.cash.app.ui.popupwindow.VitafGeneralPopup
import com.vitaf.cash.app.utils.VitafDensityUtil
import com.vitaf.cash.app.utils.helper.VitafProcessHp
import com.vitaf.cash.app.utils.log.VitafLog
import com.vitaf.cash.app.utils.receiver.VitafCheckMobileBroadcastReceiver
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import com.vitaf.cash.app.utils.shared.VitafSharedKey
import com.vitaf.cash.app.weight.font.LexendSemiBoldButton
import com.vitaf.cash.app.weight.pickerview.builder.TimePickerBuilder
import com.vitaf.cash.app.weight.pickerview.listener.OnTimeSelectListener
import com.vitaf.cash.app.weight.pickerview.view.TimePickerView
import com.vitaf.cash.lib.adapter.VitafOnSingleClickListener
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:41
 * @Annotation：账号验证页面
 */
class VitafVerifyMobileAct: VitafComAct(){
    private var _binding: VitafActVerifyMobilePageBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit verify mobile binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var sendSuccessDialog: VitafSubmitSuccessDlog? = null
    private var smsBroadcastReceiver: VitafCheckMobileBroadcastReceiver? = null

    private val SMS_CONSENT_REQUEST = 200
    var eventRemark = ""

    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 60

    private var typeList = arrayListOf<JSONObject>()
    //选择类型  SMS  、 WHATSAPP
    private var selectType = ""
    //是否需要选择出生日期
    private var needSubmitBirthDay = "NO"
    //出生日期选择
    private var pvStartDateView: TimePickerView? = null

    companion object {
        fun start(context: Context) {
            //当前栈顶是 手机号校验页面 不重复跳转
            if (VitafActStackManager.isCurrentActivity(VitafVerifyMobileAct::class.java)){
                return
            }
            val intent = Intent(context, VitafVerifyMobileAct::class.java)
            context.startActivity(intent)
        }
    }
    override fun createVitafContentView(): View {
        _binding = VitafActVerifyMobilePageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initializeVitafViews() {
        eventRemark = "Check Mobile Page"
        setBackExit(true)
        getTitleBarManager()
            .setVisibility(View.VISIBLE)
            .setBackButtonVisibility(View.GONE)
            .setTitleVisibility(View.GONE)
            .setRightButtonIcon(R.mipmap.gombe_credit_image_customer_black_icon)
            .setRootBackgroundColor(getColor(R.color.white))

        initRefreshView()
        showChcekMobileTypeView(false)

        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun setupVitafEventListeners() {
        //客服
        setRightButtonClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog(eventRemark)
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,eventRemark)
            }
        })
        _binding?.editCode?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                _binding?.btnSubmit?.isEnabled = selectType.isNotEmpty() && takeGombeCreditCheckMobileCode().isNotEmpty()
            }
        })
        _binding?.editMobile?.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                _binding?.btnConfirm?.isEnabled = takeGombeCreditCheckMobile().isNotEmpty()
                _binding?.textMobile?.text = takeGombeCreditCheckMobile()
            }
        })

        //切换校验类型
        _binding?.verifyTypeLayout?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                _binding?.let {
                    showSelectPopupwindow(it.verifyTypeLayout)
                }
            }
        })

        _binding?.btnSend?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                if (selectType.isEmpty()){
                    return
                }
                sendCheckNumberWhatsAppCodeAction()
            }
        })

        _binding?.imgEdit?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showChcekMobileTypeView(true)
            }
        })
        _binding?.btnConfirm?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                if (takeGombeCreditCheckMobile().isEmpty()){
                    return
                }
                _binding?.textMobile?.text = takeGombeCreditCheckMobile()
                showChcekMobileTypeView(false)
            }
        })
        //提交
        _binding?.btnSubmit?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                if (takeGombeCreditCheckMobile().isEmpty() || takeGombeCreditCheckMobileCode().isEmpty()){
                    _binding?.btnSubmit?.isEnabled = false
                    return
                }
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.VERIFICATION_CONTINUE,"${takeGombeCreditCheckMobileCode()}##${takeGombeCreditCheckMobile()}")
                // TODO: 校验手机号点完成 需上报所有埋点
                VitafPointManager.getInstance().manualReport()

                onCheckNumberVerificationCodeAction()
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun loadVitafData() {
        val zoneCode = VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_TIMEZONE_CODE)
        val mobile = VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_MOBILE)
        _binding?.textZoneCode?.text = "+$zoneCode"
        _binding?.textMobile?.text = mobile
        _binding?.editMobile?.setText(mobile)

        _binding?.btnSend?.text = getString(R.string.vitaf_btn_send)
        _binding?.btnSend?.isEnabled = false

        typeList.clear()
        if (VitafProcessHp.isGombeCreditCheckSMS()){
            val item = JSONObject()
            item.put("value",getString(R.string.gombe_credit_verify_mobile_type_sms))
            item.put("title",getString(R.string.gombe_credit_verify_mobile_type_sms))
            typeList.add(item)
        }
        if (VitafProcessHp.isGombeCreditCheckWhatsApp()){
            val item = JSONObject()
            item.put("value",getString(R.string.gombe_credit_verify_mobile_type_whatsapp))
            item.put("title",getString(R.string.gombe_credit_verify_mobile_type_whatsapp))
            typeList.add(item)
        }
        showDefaultCheckTypeView()
        showGombeCreditCheckMobileTipsDialog()
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        smsBroadcastReceiver = VitafCheckMobileBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(smsBroadcastReceiver, intentFilter, SmsRetriever.SEND_PERMISSION, null, Context.RECEIVER_EXPORTED)// 指定导出标志
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(smsBroadcastReceiver, intentFilter, SmsRetriever.SEND_PERMISSION, null)
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(smsBroadcastReceiver, intentFilter)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                VitafLog.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                VitafLog.e("Sms code: $code")
                if (code != null){
                    _binding?.editCode?.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                VitafLog.e("User canceled or no message received")
            }
        }
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        _binding?.checkRefreshLayout?.setColorSchemeResources(R.color.theme,R.color.purple_500)
        _binding?.checkRefreshLayout?.setOnRefreshListener {
            publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
        }
    }

    /**
     * 获取手机号
     */
    fun takeGombeCreditCheckMobile(): String {
        return _binding?.editMobile?.text.toString().trim()
    }

    /**
     * 获取验证码
     */
    fun takeGombeCreditCheckMobileCode(): String {
        return _binding?.editCode?.text.toString().trim()
    }

    /**
     * 切换校验类型
     */
    private fun setCheckNumberType(type: String,isSend: Boolean = true){
        if (selectType == type){
            return
        }
        selectType = type
        showGombeCreditCheckMobileType(type)
        if (isSend){
            sendCheckNumberWhatsAppCodeAction()
        }
    }

    /**
     * 切换是否修改手机号View
     */
    private fun showChcekMobileTypeView(isEdit: Boolean){
        _binding?.let {
            //是否允许修改手机号码
            if (!VitafProcessHp.isGombeCreditMobileEditFlag()){
                it.showMobileLayout.visibility = View.VISIBLE
                it.imgEdit.visibility = View.INVISIBLE
                it.showEditLayout.visibility = View.GONE
                return
            }
            when(isEdit){
                true -> {
                    it.showMobileLayout.visibility = View.GONE
                    it.showEditLayout.visibility = View.VISIBLE
                    onShowSoftInput(it.editMobile)
                    it.editMobile.setSelection(takeGombeCreditCheckMobile().length)
                }
                else -> {
                    it.showMobileLayout.visibility = View.VISIBLE
                    it.imgEdit.visibility = View.VISIBLE
                    it.showEditLayout.visibility = View.GONE
                }
            }
        }
    }

    /**
     * 设置默认选中校验类型
     */
    private fun showDefaultCheckTypeView(){
        //设置默认选中：有SMS就选中SMS，否则选中WHATSAPP
        if (VitafProcessHp.isGombeCreditCheckSMS()){
            setCheckNumberType("SMS",false)
        } else {
            setCheckNumberType("WHATSAPP",false)
        }
    }

    /**
     * 切换校验类型
     */
    private fun showGombeCreditCheckMobileType(type: String) {
        _binding?.btnSend?.isEnabled = true
        when(type){
            "SMS" -> {
                _binding?.textVerifyTypeTitle?.text = String.format(getString(R.string.gombe_credit_verify_mobile_type),getString(R.string.gombe_credit_verify_mobile_type_sms))
                _binding?.textVerifyType?.text = getString(R.string.gombe_credit_verify_mobile_type_sms)
            }
            else -> {
                _binding?.textVerifyTypeTitle?.text = String.format(getString(R.string.gombe_credit_verify_mobile_type),getString(R.string.gombe_credit_verify_mobile_type_whatsapp))
                _binding?.textVerifyType?.text = getString(R.string.gombe_credit_verify_mobile_type_whatsapp)
            }
        }
        _binding?.btnSubmit?.isEnabled = takeGombeCreditCheckMobileCode().isNotEmpty()
    }

    /**
     * 验证码发送成功
     * 当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
     */
    fun showGombeCreditCheckMobileSendCodeSuccess(directLoginFlag: String) {
        hideVitafLoading()
        when(directLoginFlag){
            "YES" -> {
                showGombeCreditCheckMobileSuccess()
            }
            else -> {
                startCountdownTimer()
            }
        }
    }

    /**
     * 需要选择出生日期
     */
    private fun showGombeCreditCheckMobileChooseBirthdayDialog() {
        //开始选择时间
        if(pvStartDateView == null){
            //时间可选范围18-100岁
            //当前日期
            val curtDate = Calendar.getInstance()
            val startDate = Calendar.getInstance()
            startDate.timeInMillis = curtDate.timeInMillis
            startDate.add(Calendar.YEAR,-100)

            val endDate = Calendar.getInstance()
            endDate.timeInMillis = curtDate.timeInMillis
            endDate.add(Calendar.YEAR,-18)

            pvStartDateView = TimePickerBuilder(this, object : OnTimeSelectListener {
                override fun onTimeSelect(date: Date?, v: View?) {
                }

                @SuppressLint("SimpleDateFormat")
                override fun onTimeSelectString(date: Date?, showDate: String?) {
                    date?.let {
                        val value = SimpleDateFormat("yyyy-MM-dd").format(it)
                        onCheckNumberVerificationCodeAction(value)
                    }
                }
            })
                .setDate(endDate) //默认选中
                .setRangDate(startDate, endDate) //可选择时间范围
                .setLayoutRes(R.layout.vitaf_dlog_birthdate) { v ->
                    val ivClose = v.findViewById<ImageView>(R.id.imgClose)
                    ivClose.setOnClickListener {
                        pvStartDateView?.dismiss()
                    }
                    //确定
                    val btnConfirm = v.findViewById<LexendSemiBoldButton>(R.id.btnConfirm)
                    btnConfirm.setOnClickListener {
                        pvStartDateView?.returnData()
                        pvStartDateView?.dismiss()
                    }
                }
                .isDialog(true)
                .setContentTextSize(16)
                .setType(booleanArrayOf(true, true, true, false, false, false))
                .setLabel("", "", "", "", "", "")
                .setLineSpacingMultiplier(3.5f)
                .setTextXOffset(65, 65, 65, 65, 65, 65)
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(getColor(R.color.gombe_credit_ff1d1e20)) //设置选中项文字颜色
                .setTextColorOut(getColor(R.color.gombe_credit_ffc8c8c8))//默认颜色
                .setBgColor(getColor(R.color.transparent))
                .isAlphaGradient(true)
                .setItemVisibleCount(3)
                .isCyclic(true)
                .setDividerColor(getColor(R.color.transparent))
                .build()
            val dialog = pvStartDateView?.dialog
            dialog?.let {
                val dialogWindow = it.window
                if (dialogWindow != null) {
                    val params = dialogWindow.attributes
                    params.width = WindowManager.LayoutParams.MATCH_PARENT
                    params.height = WindowManager.LayoutParams.WRAP_CONTENT
                    dialogWindow.attributes = params
                    dialogWindow.setWindowAnimations(R.style.dialog_scale_anim) //修改动画样式
                    dialogWindow.setGravity(Gravity.CENTER)
                    dialogWindow.setDimAmount(0.3f)
                }
            }
        }
        pvStartDateView?.show()

    }

    /**
     * 校验成功
     */
    fun showGombeCreditCheckMobileSuccess() {
        VitafSharedHp.addGombeCreditSharedData(VitafSharedKey.GOMBECREDIT_MOBILE, takeGombeCreditCheckMobile())
        publishEventData(VitafEventData(VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 发送成功提示
     */
    private fun showSendCodeSuccessDialog(){
        if (sendSuccessDialog == null){
            sendSuccessDialog = VitafSubmitSuccessDlog(this)
            sendSuccessDialog?.setCancelable(true)
            sendSuccessDialog?.setCanceledOnTouchOutside(false)
        }
        sendSuccessDialog?.show()
        sendSuccessDialog?.setTipsSuccessText(getString(R.string.gombe_credit_verify_mobile_send_success_tips))
        lifecycleScope.launch {
            delay(1500)
            sendSuccessDialog?.dismiss()
        }
    }

    /**
     * 提示dialog
     */
    private fun showGombeCreditCheckMobileTipsDialog(){
        val tipsDialog = VitafTipsDlog(this)
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.addGombeCreditKindTipsEventRemark(eventRemark)
        tipsDialog.setGombeCreditKindTipsTitleText(getString(R.string.vitaf_dlog_notice))
        tipsDialog.setGombeCreditKindTipsMsgText(getString(R.string.gombe_credit_verify_mobile_dialog_tips))
        tipsDialog.setGombeCreditKintTipsButtonConfirmText(getString(R.string.gombe_credit_verify_mobile_dialog_understand))
        tipsDialog.isGombeCreditKindTipsDoubleButton(false)
    }

    /**
     * 选择选项
     */
    private fun showSelectPopupwindow(view: View){
        _binding?.imageVerifyTypeCursor?.setImageResource(R.mipmap.gombe_credit_image_up_black_icon)
        val selectPopup = VitafGeneralPopup(this)
        selectPopup.setWindowWidth(view.width + VitafDensityUtil.dp2px(10f))
        selectPopup.setSelectItemListener(object : VitafGeneralPopup.IItemClickListener {
            //完成
            override fun onConfirmAction(data: JSONObject?) {
                data?.let {
                    val subRemark = "${data.optString("value")}$$${data.optString("duration")}"
                    when(it.optString("value")){
                        getString(R.string.gombe_credit_verify_mobile_type_sms) -> {
                            setCheckNumberType("SMS")
                            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.VERIFICATION_SMS,subRemark)
                        }
                        else -> {
                            setCheckNumberType("WHATSAPP")
                            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.VERIFICATION_WHATSAPP,subRemark)
                        }
                    }
                }
            }
            //关闭监听
            override fun onDismissListener() {
                _binding?.imageVerifyTypeCursor?.setImageResource(R.mipmap.gombe_credit_image_down_black_icon)
            }
        })
        _binding?.let {
            selectPopup.show(view, it.root)
            selectPopup.setBrandList(typeList)
        }
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    class MyCountDownTimer(private val act: VitafVerifyMobileAct, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showCheckCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showCheckCountdownComplete()
        }
    }

    /**
     * 倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun showCheckCountdownText(){
        _binding?.btnSend?.text = "$countdown S"
    }

    /**
     * 倒计时完成
     */
    private fun showCheckCountdownComplete(){
        countdown = 60
        _binding?.btnSend?.text = getString(R.string.vitaf_btn_send)
        _binding?.btnSend?.isEnabled = true
        _binding?.verifyTypeLayout?.isEnabled = true
        showChcekMobileTypeView(false)
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountdownTimer() {
        showSendCodeSuccessDialog()
        //随机 60秒 等待时长
        countdown = 60
        _binding?.btnSend?.text = "$countdown S"
        _binding?.btnSend?.isEnabled = false
        _binding?.verifyTypeLayout?.isEnabled = false
        //手机号码输入框变成不可编辑状态
        _binding?.showMobileLayout?.visibility = View.VISIBLE
        _binding?.imgEdit?.visibility = View.INVISIBLE
        _binding?.showEditLayout?.visibility = View.GONE

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    override fun onVitafPublishEvent(event: VitafEventData) {
        super.onVitafPublishEvent(event)
        when(event.eventType){
            VitafEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> {
                hideVitafLoading()
                //需要校验 WhatsApp 或 SMS
                if (!VitafProcessHp.isGombeCreditCheckWhatsApp() && !VitafProcessHp.isGombeCreditCheckSMS()){
                    //校验成功
                    showGombeCreditCheckMobileSuccess()
                }
            }
            else -> {

            }
        }
    }

    override fun hideVitafLoading() {
        super.hideVitafLoading()
        _binding?.checkRefreshLayout?.isRefreshing = false
    }

    /**
     * 发送WhatsApp验证码
     */
    private fun sendCheckNumberWhatsAppCodeAction(){
        //发送验证，埋点增加手机号
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.VERIFICATION_GETCODE,takeGombeCreditCheckMobile())
        showVitafLoading()
        val loginMobile = VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_WHATSAPP_SEND_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", takeGombeCreditCheckMobile())
            put("sendType",selectType)
        }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //是否需要验证生日
                    if (obj.has("needSubmitBirthDay")){
                        needSubmitBirthDay = obj.optString("needSubmitBirthDay")
                    }
                    //当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
                    val directLoginFlag = obj.optString("directLoginFlag")
                    showGombeCreditCheckMobileSendCodeSuccess(directLoginFlag)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    /**
     * 校验验证码
     */
    fun onCheckNumberVerificationCodeAction(submitBirthDay: String = ""){
        //需要提交出生日期
        if (needSubmitBirthDay == "YES" && submitBirthDay.isEmpty()){
            showGombeCreditCheckMobileChooseBirthdayDialog()
            return
        }
        showVitafLoading()
        val loginMobile = VitafSharedHp.takeGombeCreditSharedString(VitafSharedKey.GOMBECREDIT_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_WHATSAPP_CHECK_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", takeGombeCreditCheckMobile())
            put("code",takeGombeCreditCheckMobileCode())
            put("checkType",selectType)
            put("needSubmitBirthDay",needSubmitBirthDay)//是否需要验证生日
        }
        if (needSubmitBirthDay == "YES" && submitBirthDay.isNotEmpty()){
            params.put("submitBirthDay",submitBirthDay)//出生日期
        }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideVitafLoading()
                showGombeCreditCheckMobileSuccess()
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.VERIFICATION_SMS_START, eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.VERIFICATION_SMS_END, eventRemark)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        if (smsBroadcastReceiver != null){
            unregisterReceiver(smsBroadcastReceiver)
        }
        _binding = null
    }
}